package com.vm.utils;

import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.widget.ImageView;

public class BitmapUtil {

	public static void relaseAllBitmap(View view) {

		if (view instanceof ViewGroup) {
			ViewGroup viewGroup = (ViewGroup) view;

			int count = viewGroup.getChildCount();
			if (count > 0) {
				try {
					for (int i = 0; i < count; i++) {

						View v = viewGroup.getChildAt(i);
						if (v instanceof ImageView) {
							BitmapUtil.releaseImageView((ImageView) v);
						} else {
							relaseAllBitmap(v);
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					Log.e("relaseAllBitmap", e.getMessage());
				}

			}
		} else {
			if (view instanceof ImageView) {
				BitmapUtil.releaseImageView((ImageView) view);
			}
		}
	}

	/**
	 * 释放图片，主动释放Bitmap资源
	 * 
	 * @param imageView
	 */
	public static void releaseImageView(ImageView imageView) {
		if (imageView != null) {
			imageView.measure(
					MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
					MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
			imageView.layout(0, 0, imageView.getMeasuredWidth(),
					imageView.getMeasuredHeight());
			imageView.buildDrawingCache();
			Bitmap bitmap = imageView.getDrawingCache();
			releaseBitmap(bitmap);
			imageView.setImageBitmap(null);
		}
	}

	/**
	 * 释放Bitmap资源
	 * 
	 * @param bitmap
	 */
	public static void releaseBitmap(Bitmap bitmap) {
		if (bitmap != null && !bitmap.isRecycled()) {
			bitmap.recycle();
			bitmap = null;
		}
	}

}
